package sisi.currency;

import java.util.List;

import javax.persistence.EntityManager;

/*
* CurrencyControllerWindow.java - Controller class for <i>currency database table</i>. 
* @author Pedro Gonzalez pedro@sisisoftware.it
* @author Claudio Pelosi claudio@sisisoftware.it
* @author SISI Software S.n.c. - www.sisisoftware.it
* @version 1.0, 07/07/2014
* 
*/
public class CurrencyController{

	private EntityManager getEntityManager() {
		return new sisi.MyEmf().getEntityManager();
	}

	public Currency[] get(String cerca) {
		List<Currency> lista = getList(cerca);
			return lista.toArray(new Currency[0]);
		}

	@SuppressWarnings("unchecked")
	public List<Currency> getList(String cerca) {

		String cWhere = "";
		if (cerca != null && !cerca.isEmpty()) {
			cWhere = " WHERE TRIM( BOTH FROM UPPER(c.currdesc) ) LIKE :cerca ";
		}

		EntityManager em = getEntityManager();
		try {
			javax.persistence.Query q = em
				.createQuery("select c from Currency as c " + cWhere 
					+ " order by c.curr ");

			if (cerca != null && !cerca.isEmpty()) {
				q.setParameter("cerca", '%'+cerca.trim().toUpperCase()+'%' );
			}

			List<Currency> lista = q.getResultList();
			return lista;
		} finally {
			em.close();
		}
	}

	public Currency getxId(int id) {

		EntityManager em = getEntityManager();
		try {
			Currency currencyx = em.find(Currency.class, id);
			return currencyx;
		} finally {
			em.close();
		}
	}

	@SuppressWarnings("finally")
	public Currency add(Currency currency) {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(currency);
			em.getTransaction().commit();
			currency = refresh(currency);
		} finally {
			em.close();
			return currency;
		}
	}

	@SuppressWarnings("finally")
	public boolean update(Currency currency) {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			Currency currencyx = em.find(Currency.class, currency.getId());
			currencyx.setId(currency.getId());
			currencyx.setCurr(currency.getCurr());
			currencyx.setCurrdesc(currency.getCurrdesc());
			em.getTransaction().commit();
			em.flush();

		} finally {
			em.close();
		return false;
		}
	}

@SuppressWarnings("finally")
public Currency refresh(Currency currency) {

		Currency currencyx = currency;
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			currencyx = em.find(Currency.class, currency.getId());
			em.flush();
			em.refresh(currencyx);
		} finally {
			em.close();
			return currencyx;
		}
}

@SuppressWarnings("finally")
public boolean remove(Currency currency) {
		EntityManager em = getEntityManager();
		try {
			em.getTransaction().begin();
			Currency currencyx = em.find(Currency.class, currency.getId());
			em.remove(currencyx);
			em.getTransaction().commit();
		} finally {
			em.close();
			return false;
		}
}

}
//
// fine
